#pragma onece

#include <libudev.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;

#include "../CameraInfo.h"

#define HP_VID "2D90"

namespace movesense {

class Device
{
public:
	Device() {}

	vector<CameraInfo> cameraInfoList;

	// Return the number of camera connected to PC
	int ScanCameras()
	{
		cameraInfoList.clear();

		int cnt = 0;
		
		struct udev *udev;
		struct udev_enumerate *enumerate;
		struct udev_list_entry *devices, *dev_list_entry;
		struct udev_device *dev,*devlw;
		char* dev_name = NULL;
		char index_cnt = 50;
		char flag = 0;

		char device[index_cnt][10];
		
		for(int i=0; i<index_cnt; i++)
		{
			sprintf(device[i],"video%d",i);
		}

		for(int index=0;index<index_cnt;index++)
		{
			udev = udev_new();
			if (!udev) {
				break;
			}
			enumerate = udev_enumerate_new(udev);
			udev_enumerate_add_match_sysname(enumerate,device[index]);
			udev_enumerate_scan_devices(enumerate);
			devices = udev_enumerate_get_list_entry(enumerate);
			udev_list_entry_foreach(dev_list_entry, devices)
			{
				const char *path;
				path = udev_list_entry_get_name(dev_list_entry);
				dev = udev_device_new_from_syspath(udev, path);
				char *dev_path = (char *)udev_device_get_devnode(dev);
				devlw = udev_device_get_parent_with_subsystem_devtype(dev, "usb","usb_device");
				if (!dev) {
					printf("Unable to find parent usb device.\n");
				}
				char* vvid = (char*)udev_device_get_sysattr_value(devlw,"idVendor");
				char* ppid =(char*)udev_device_get_sysattr_value(devlw, "idProduct");
				if(vvid != NULL && ppid != NULL)
				{
					if((strcasecmp(vvid,HP_VID)) == 0)
					{
						dev_name=dev_path;
						CameraInfo ci;
						ci.devName = dev_path;
						ci.vid = HP_VID;
						ci.pid = strupr(ppid);
						ci.serialNum = "";
						ci.usbVer = ppid[3]=='2'? "2.0" : "3.0";

						cameraInfoList.push_back(ci);
						cnt++;
					}
				}
				udev_device_unref(dev);
			}
			udev_enumerate_unref(enumerate);
			udev_unref(udev);
		}
		
		return cnt;
	}
	
	char *strupr(char *str){
		char *orign=str;
		for (; *str!='\0'; str++)
			*str = toupper(*str);
		return orign;
	}

};

}
